<template>
  <div id="login-container" @click.stop="openLoginDialog">
    <img class="avatar" src="../../assets/img/avatar2.svg" alt="404"/>
    <transition name="fade">
      <div id="login-dialog" v-if="visible" @click.stop="">
        <div id="dialog-container"
             :class="{ 'animate__animated animate__bounceInDown animate__fast' : visible,
             'login-height': formType === 'login', 'register-height': formType === 'register'}">
          <span class="close-button" @click.stop="handleClose">&times;</span>
          <div class="login-logo">
            <img class="animate__animated animate__flipInX"
                 src="../../assets/icon/login/we-roast-logo-new.png" alt="">
          </div>
          <span class="divider"/>
          <div class="form-box" :class="{'login-form': formType === 'login', 'register-form': formType === 'register'}"
               @click.stop="">
            <!-- 登录表单 -->
            <el-form v-if="formType === 'login'" ref="loginForm" label-position="left" status-icon :model="formData"
                     label-width="60px"
                     :rules="rules" hide-required-asterisk>
              <el-form-item label="账号" prop="account">
                <el-input v-model="formData.account" placeholder="请输入手机号/邮箱" maxlength="50"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password" show-message>
                <el-input type="password" v-model="formData.password" placeholder="请输入密码" show-password
                          maxlength="50" @keyup.enter.native="login"></el-input>
              </el-form-item>
              <el-form-item label="验证码" prop="code" v-if="failCount >= 3">
                <div class="code-box" v-loading="captchaLoading">
                  <el-input class="code-input" v-model="formData.code" placeholder=""></el-input>
                  <img class="code-img" :src="captchaUrl" alt="" @click.stop="flashCaptcha"/>
                </div>
              </el-form-item>
            </el-form>

            <!-- 注册表单 -->
            <el-form v-if="formType === 'register'" ref="registerForm" label-position="left" status-icon
                     :model="formData" label-width="70px"
                     :rules="rules" hide-required-asterisk>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="100"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password" show-message>
                <el-input type="password" v-model="formData.password" placeholder="请输入密码" show-password
                          maxlength="50"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="checkPass" show-message>
                <el-input type="password" v-model="formData.checkPass" placeholder="请再次输入密码" show-password
                          maxlength="50"></el-input>
              </el-form-item>
              <el-form-item label="验证码" prop="code">
                <div class="code-box" v-loading="captchaLoading">
                  <el-input class="code-input" v-model="formData.code" placeholder="请输入验证码"></el-input>
                  <img class="code-img" :src="captchaUrl" alt="" @click.stop="flashCaptcha"/>
                </div>
              </el-form-item>
            </el-form>

            <!-- 按钮 -->
            <div class="button-box">
              <el-button :loading="buttonLoading"
                         :class="{ 'theme-button' :formType === 'login', 'register-button' :formType === 'register'}"
                         type="primary" @click.stop="formType === 'login' ? login() : register()">
                {{ formType === 'login' ? '登录' : '注册' }}
              </el-button>
              <div class="text-btn">
                <el-button style="color: var(--theme-color); height: 10px" size="small" type="text"
                           @click.stop="switchForm">
                  {{ formType === 'login' ? '注册账号' : '有账号了，去登录' }}
                </el-button>
                <el-button v-if="formType === 'login'" style="color: var(--theme-color); height: 10px" size="small"
                           type="text" @click.stop="openFPW()">
                  忘记密码
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <el-dialog
            append-to-body
            title="忘记密码"
            :visible.sync="forgetPwdWindow"
            width="50%"
            :before-close="handleFPWClose">
          <div id="forget-pwd-container">
            <el-steps style="width: 70%;" :active="step" finish-status="success" align-center>
              <el-step title="发送邮箱"></el-step>
              <el-step title="设置新密码"></el-step>
            </el-steps>
            <div class="from-box">
              <!-- 邮箱验证表单 -->
              <el-form v-if="step === 0" ref="emailCheckForm" label-position="left" status-icon
                       :model="formData" label-width="70px"
                       :rules="rules" hide-required-asterisk>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="100"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                  <div class="code-box" v-loading="captchaLoading">
                    <el-input class="code-input" v-model="formData.code" placeholder="请输入验证码"></el-input>
                    <img class="code-img" :src="captchaUrl" alt="" @click.stop="flashCaptcha"/>
                  </div>
                </el-form-item>
                <div style="width: 100%; display: flex; justify-content: center">
                  <el-button v-loading="buttonLoading" type="primary" size="medium" @click.stop="sendEmailCode">发送邮箱验证码</el-button>
                </div>
              </el-form>

              <!-- 邮箱表单 -->
              <el-form v-if="step === 1" ref="resetPwdForm" label-position="left" status-icon
                       :model="formData" label-width="90px"
                       :rules="rules" hide-required-asterisk>
                <el-form-item label="新密码" prop="password" show-message>
                  <el-input type="password" v-model="formData.password" placeholder="请输入新密码" show-password
                            maxlength="50"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass" show-message>
                  <el-input type="password" v-model="formData.checkPass" placeholder="请再次输入密码" show-password
                            maxlength="50"></el-input>
                </el-form-item>
                <el-form-item label="邮箱验证码" prop="code">
                  <el-input class="code-input" v-model="formData.emailCode" placeholder="请输入邮箱验证码"></el-input>
                </el-form-item>
                <div style="width: 100%; display: flex; justify-content: center">
                  <el-button type="primary" size="medium" @click.stop="() => step = 0">上一步</el-button>
                  <el-button v-loading="buttonLoading" type="primary" size="medium" @click.stop="resetPwd">修改密码</el-button>
                </div>
              </el-form>
            </div>
          </div>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script>
import {getCaptcha, login, register, resetPwd, sendEmailCode} from "@/api/authApi";
import {setToken} from "@/util/auth";
import bus from "@/bus/bus";

export default {
  name: "loginPage",
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.formType === 'register') {
          // 校验密码格式（至少8位数，包含大小写字母）
          if (!/^(?=.*[a-z])(?=.*[A-Z]).{8,}$/.test(value)) {
            callback(new Error('密码至少8位数，包含大小写字母'));
          }
          this.$refs.registerForm.validateField('checkPass');
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.formData.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      formType: 'login',
      visible: false,
      buttonLoading: false,
      captchaLoading: false,
      forgetPwdWindow: false,
      captchaUrl: '',
      failCount: 0,
      step: 0,
      formData: {
        account: 'kk@qq.com',
        password: '111111Kj',
      },
      rules: {
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱', trigger: 'blur'}
        ],
        account: [
          {required: true, message: '请输入手机号/邮箱'},
        ],
        password: [
          {validator: validatePass, trigger: 'blur'}
        ],
        checkPass: [
          {validator: validatePass2, trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入验证码'},
        ]
      }
    }
  },
  methods: {
    flashCaptcha() {
      this.captchaLoading = true
      getCaptcha().then(res => {
        this.captchaUrl = res.data.img
        this.captchaLoading = false
      })
    },
    login() {
      this.$refs['loginForm'].validate(valid => {
        if (!valid) return;
        this.buttonLoading = true
        login(this.formData).then(res => {
          this.$message.success('登录成功')
          // 保存token
          setToken(res.data.token, res.data.userName)
          this.handleClose()
          this.$emit('flashNavBox')
        }, error => {
          if (error.code === 'A02011') {
            this.failCount = 5
          }
          if (error.code !== 'A02000' || error.code !== 'B00001') {
            this.failCount++;
          }
        })
        this.buttonLoading = false
      })
    },
    register() {
      this.$refs['registerForm'].validate(valid => {
        if (!valid) return;
        this.buttonLoading = true
        register(this.formData).then(() => {
          // 取出邮箱
          let email = this.formData.email
          this.$message.success('注册成功')
          // 切换登录表单并填充邮箱
          this.switchForm()
          this.formData.account = email
        });
        this.buttonLoading = false
      })
    },
    switchForm() {
      this.formData = {}
      if (this.formType === 'login') {
        this.formType = 'register'
        this.flashCaptcha()
        this.$refs['loginForm'].resetFields()
        return
      }
      this.formType = 'login'
      this.$refs['registerForm'].resetFields()
    },
    openLoginDialog() {
      this.visible = true
      this.formType = 'login'
      this.formData = {
        account: '',
        password: '',
      }
    },
    handleClose() {
      this.visible = false
    },
    openFPW() {
      this.forgetPwdWindow = true
      this.flashCaptcha()
      this.step = 0
      this.formData = {}
    },
    handleFPWClose() {
      this.forgetPwdWindow = false
      this.step = 0
    },
    sendEmailCode() {
      this.$refs['emailCheckForm'].validate(valid => {
        if (!valid) return;
        this.buttonLoading = true
        let data = {
          email: this.formData.email,
          code: this.formData.code
        }
        sendEmailCode(data).then(res => {
          if (res.code === '200') {
            this.$message.success('验证码已发送，请注意查收')
            this.step = 1
          }
        }).finally(() => {
          this.buttonLoading = false
        });
      })
    },
    resetPwd() {
      this.$refs['resetPwdForm'].validate(valid => {
        if (!valid) return;
        this.buttonLoading = true
        let data = {
          email: this.formData.email,
          emailCode: this.formData.emailCode,
          newPwd: this.formData.password
        }
        resetPwd(data).then(res => {
          if (res.code === '200') {
            this.$message.success('密码重置成功')
            this.handleFPWClose()
          }
        }).finally(() => {
          this.buttonLoading = false
        })
      })
    }
  },
  watch: {
    failCount: function (val) {
      if (val >= 3) {
        this.flashCaptcha()
      }
    }
  },
  created() {
    // 注册全局事件
    bus.$on('goToLogin', () => {
      this.openLoginDialog()
    })
  },
  beforeDestroy() {
    bus.$off('goToLogin')
  }
}
</script>


<style scoped lang="scss">
@import url("@/scss/loginBox.scss");
</style>